<template>
	<!-- <view class="margin-top"> -->
	<view>
		<view class="cu-bar bg-white " style="height: 30px;line-height: 30px;min-height: 30px;">
			<view class="action">
				{{label}}
			</view>
			<view class="action">
				{{imgList.length}}/{{maxImg}}
			</view>
		</view>
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage(item,index)"
					:data-url="imgList[index]">
					<!-- <image v-if="!item.isBase" :src="imgList[index]" mode="aspectFill"></image> -->
					<image v-if="!item.isBase" :src="item.imageThumbnail" mode="aspectFill"></image>
					<image v-if="item.isBase" :src=" 'data:image/png;base64,' + item.imageThumbnail"
						style="width: 100%;"></img>
						<view class="cu-tag bg-red" @tap.stop="DelImg(index)" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length<maxImg">
					<text class='cuIcon-cameraadd'></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import configService from '@/common/service/config.service.js'
	import { pathToBase64, base64ToPath } from '@/js_sdk/mmmm-image-tools'
	
	import {
		ACCESS_TOKEN
	} from '@/common/util/constants.js'

	import store from '@/store/index.js';
	import api from '@/api/api'
	let apiUrl = configService.apiUrl;
	export default {
		name: 'MyImageUpoad',
		props: {
			value: {
				type: String,
				default: ''
			},
			value2: {
				type: Array,
				default: []
			},
			label: {
				type: String,
				default: '图片上传'
			},
			isBase: {
				type: Boolean,
				default: false
			},
			maxImg: {
				type: Number,
				default: 8
			},
			

		},
		mounted() {
		
			console.log(this.isBase)
			if (this.isBase) {
				//方法无用，刚进来获取this.imgList2为空，通过watch方法
				console.log(this.imgList2)
				// if (this.imgList2.length) {
				// 	this.imgList2.forEach(e => {

				// 		this.pathlist.push(e.imageId)
				// 		let picUrl = `${apiUrl}/sys/common/static/${e.imageId}`;
				// 		this.imgsArray.push(picUrl)
				// 	})
				// 	this.imgList = this.imgList2
				// 	console.log(this.imgList)
				// }
			} else {
				if (this.value.split(',') != '') {
					this.value.split(',').forEach(res => {
						this.imgList.push(apiUrl + '/' + res)
					})
				}
			}

		},
		watch: {
			value2: {
				handler(val, oldName) {
					console.log(this.hasload)
					if (!this.hasload && val && val.length) {
						this.hasload = true;
						this.imgList2 = JSON.parse(JSON.stringify(val));
						this.imgList2.forEach(e => {
							e.isBase = true
						})
						this.imgList = this.imgList2
						this.imgList.forEach(e => {
							this.pathlist.push(e.imageId)
							let picUrl = `${apiUrl}/sys/common/static/${e.imageId}`;
							this.imgsArray.push(picUrl)
						})
						// this.pathlist.join(',')
						// this.value2.forEach(res=>{
						// 	this.imgList.push(res)
						// })
						console.log(this.imgList)
					}
				},
				immediate: true,
				deep: true
			}
		},
		data() {
			return {
				hasload: false,
				imgList: [],
				imgList2: [],
				pathlist: [],
				//图片预览url
                imgsArray: [],
			}
		},
		methods: {

			ChooseImage() {

				var token = ''
				try {
					token = uni.getStorageSync(ACCESS_TOKEN)
				} catch (e) {
					//TODO handle the exception
					console.log("getTokenStorage", token)
				}

				uni.chooseImage({
					// count: this.maxImg, //默认9
					count: 1, 
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						uni.uploadFile({
							// url: `${apiUrl}/systemController/filedeal.do?isup=1`,
							//url: `${apiUrl}/sys/oss/file/upload`,
							//url: `${apiUrl}/sys/common/upload`,
							url: `${apiUrl}/pollution/upload`,
							filePath: res.tempFilePaths[0],
							name: 'file',
							// header:{"Content-Type": "multipart/form-data"},
							header: {
								'X-Access-Token': token,
							},
							success: (uploadFileRes) => {
								let o = JSON.parse(uploadFileRes.data)
								console.log(o)
								if (o.success == true) {
									let path = JSON.parse(uploadFileRes.data).message
									this.pathlist.push(path);
	
									// this.$emit('input',this.pathlist.join(','))
									let obj = {
										imageThumbnail: res.tempFilePaths[0],
										isBase: false
									}
									this.imgList.push(obj)
									console.log(this.imgList)
									this.$emit('getData', this.pathlist.join(','));
									if (this.imgsArray.length != 0) {
										this.imgsArray = this.imgsArray.concat(res.tempFilePaths)
									} else {
										this.imgsArray = res.tempFilePaths
									}
								}


							}
						})

					}
				});
			},
			ViewImage(e, index) {
				console.log(e)
				// this.imgsArray=[]
				// this.imgList.forEach(i=>{
					
				// })
				// uni.showLoading({
				// 					title:'预览加载中'
				// 				});
				// 				let _this = this;
				// 				let imgsArray = [];
				// 				//_this.img_所要预览的base64图片路径
				// 				base64ToPath(_this.img_).then(path=>{
				// 					uni.hideLoading();
				// 					imgsArray[0] = path
				// 					uni.previewImage({
				// 						current:0,
				// 						urls:imgsArray
				// 					})
				// 				})
				//如果是编辑
				if (e.isBase) {
					//let url = `${apiUrl}/pollution/getImageId?imageId=${e.imageId}`
					
					// this.$http.get(url).then(res => {
					// 	console.log(res)
					// 	if (res.data.code == 200) {

					// 	}

					// }).catch((error) => {
					// 	console.log(error)				
					// })
					// uni.showLoading({
					// 	title: '预览加载中'
					// });
					let _this = this;
					// let imgsArray = [];
					// imgsArray[0] = picUrl
					
					let picUrl = `${apiUrl}/sys/common/static/${e.imageId}`
					console.log('预览图片数组',this.imgsArray)
					uni.previewImage({
						current: index,
						urls: this.imgsArray,
						 indicator: "number",
						success: function(data) {
							console.log('选中了张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					})
					// let pat =''
					// pat = e.imageDetails;
					// console.log(pat)
					// base64ToPath(pat).then(path => {
					// 	console.log(path)
					// 	uni.hideLoading();
					// 	imgsArray[0] = path
					// 	uni.previewImage({
					// 		current: 0,
					// 		urls: imgsArray
					// 	})
					// })

					// arr.push(url)
				} else {
					//如果是新添加的图片
					console.log('预览图片数组',this.imgsArray)
					uni.previewImage({
						urls: this.imgsArray,
						current: index,
						// current: e.currentTarget.dataset.url
					});
				}

			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确认要删除吗',
					cancelText: '取消',
					confirmText: '确认',
					success: res => {
						if (res.confirm) {
							this.pathlist.splice(e, 1)
							this.imgList.splice(e, 1)
							this.imgsArray.splice(e, 1)
							console.log(this.imgList)
							console.log(this.pathlist)
							this.$emit('getData', this.pathlist.join(','))
						}
					}
				})
			},
		}
	}
</script>

<style>

</style>
